import requests
import csv
import time


def get_treasury_bonds():
    api_url = "https://www.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoListEN"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "X-Requested-With": "XMLHttpRequest",
        "Referer": "https://www.chinamoney.com.cn/english/bdInfo/",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        # 从浏览器复制Cookie
        "Cookie": "AlteonP10=BtpeBCw/F6xC7pUp/c/YRg$$; _ulta_id.ECM-Prod.e9dc=f1c883e974a0496c; _ulta_ses.ECM-Prod.e9dc=5d60e3e539455049"  # 粘贴浏览器中的Cookie
    }


    form_data = {
        "pageNo": "1",
        "pageSize": "15",
        "isin": "",
        "bondCode": "",
        "issueEnty": "",
        "bondType": "100001",
        "couponType": "",
        "issueYear": "2023",
        "rtngShrt": "",
        "bondSpclPrjctVrty": ""
    }

    all_data = []

    try:

        response = requests.post(api_url, data=form_data, headers=headers)
        response.raise_for_status()


        print("请求参数11:", form_data)
        print("响应内容11:", response.text)

        result = response.json()
        data = result.get("data", {})
        total_pages = data.get("pageTotal", 0)
        total_records = data.get("total", 0)

        print(f"总页数：{total_pages}，总记录数：{total_records}")

        if total_records == 0:
            print("未查询到数据，请检查Cookie是否有效")
            return all_data


        for page in range(total_pages):
            form_data["pageNo"] = str(page)
            response = requests.post(api_url, data=form_data, headers=headers)
            response.raise_for_status()
            result = response.json()
            current_data = result.get("data", {})

            print(f"正在获取第{page + 1}/{total_pages}页数据...")

            current_records = current_data.get("resultList", [])
            all_data.extend(current_records)

            time.sleep(1)

    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
    except ValueError:
        print("无法解析JSON响应")
        return None

    print(f"数据获取完成，共{len(all_data)}条记录")
    return all_data


def save_to_csv(data, filename="treasury_bonds_2023.csv"):
    if not data:
        print("没有数据可保存")
        return

    field_mapping = {
        "ISIN": "isin",
        "Bond Code": "bondCode",
        "Issuer": "entyFullName",
        "Bond Type": "bondType",
        "Issue Date": "issueStartDate",
        "Latest Rating": "debtRtng"
    }

    with open(filename, "w", newline="", encoding="utf-8") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=field_mapping.keys())
        writer.writeheader()

        for item in data:
            row = {
                csv_column: item.get(json_field, "")
                for csv_column, json_field in field_mapping.items()
            }
            writer.writerow(row)

    print(f"成功保存{len(data)}条数据到{filename}")


if __name__ == "__main__":
    bond_data = get_treasury_bonds()

    if bond_data:
        save_to_csv(bond_data)
    print("操作完成")
